<template>
  <el-card class="main-card">
    <div class="title">{{!article.id ? '资讯发布' : '资讯修改'}}</div>
    <div class="article-title-container">
      <el-input v-model="article.title" size="medium" placeholder="输入资讯标题" />
      <el-button type="danger" size="medium" @click="openModel" style="margin-left: 10px"> 发布文章 </el-button>
    </div>
    <mavon-editor ref="md" v-model="article.content" @imgAdd="uploadImg" style="height: calc(100vh - 260px)" />
    <el-dialog :visible.sync="addOrEdit" width="60%" top="3vh">
      <div class="dialog-title-container" slot="title">发布资讯</div>
      <el-form label-width="100px" size="medium" :model="article">
        <el-form-item label="资讯类型">
          <el-select v-model="article.articlesTypeId" placeholder="请选择资讯类型">
            <el-option v-for="item in typeList" :key="item.id" :label="item.typeName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词设置">
          <el-input v-model="article.searchKeywords" placeholder="请填写关键词(多个用,隔开)" />
        </el-form-item>
        <el-form-item label="上传资讯封面">
          <el-upload class="avatar-uploader" :action="uploadUrl" :headers="headers" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="article.imgUrl" :src="article.imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addOrEdit = false">取 消</el-button>
        <el-button type="danger" @click="saveOrUpdateArticle"> 发 表 </el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import Cookies from 'js-cookie'
import * as imageConversion from 'image-conversion'
export default {
  activated() {
    const articleId = this.$route.params.id
    console.log('articleId' + articleId)
    if (articleId) {
      this.$http.get('/health/articles/' + articleId).then(({ data }) => {
        this.article = data.data
      })
    } else {
      const article = sessionStorage.getItem('article')
      if (article) {
        this.article = JSON.parse(article)
      }
    }
  },
  data: function () {
    return {
      uploadUrl: window.SITE_CONFIG['apiURL'] + '/piclocal/upload/pic',
      headers: { token: Cookies.get('token') },
      addOrEdit: false,
      autoSave: true,
      typeList: [],
      article: {
        id: null,
        articlesTypeId: '',
        searchKeywords: '',
        title: '',
        imgUrl: '',
        content: ''
      }
    }
  },
  methods: {
    listCategories() {
      this.$http.get('/health/articlestype/list').then(({ data }) => {
        this.typeList = data.data
      })
    },
    openModel() {
      if (this.article.title.trim() == '') {
        this.$message.error('资讯标题不能为空')
        return false
      }
      if (this.article.content.trim() == '') {
        this.$message.error('资讯内容不能为空')
        return false
      }
      this.listCategories()
      this.addOrEdit = true
    },
    handleAvatarSuccess(res, file) {
      console.log(res)
      console.log(file)
      this.article.imgUrl = res.data.imgAddress;
    },
    beforeAvatarUpload(file) {

    },
    uploadImg(pos, $file) {
      var formdata = new FormData()
      formdata.append('file', $file)
      this.$http.post('/piclocal/upload/pic', formdata).then(({ data: res }) => {
        console.log('res.imgAddress:' + res.data.imgAddress)
        this.$refs.md.$img2Url(pos, res.data.imgAddress)
      })
    },
    saveOrUpdateArticle() {
      if (this.article.title.trim() == '') {
        this.$message.error('资讯标题不能为空')
        return false
      }
      if (this.article.articlesTypeId.trim() == '') {
        this.$message.error('资讯类型不能为空')
        return false
      }
      if (this.article.searchKeywords.trim() == '') {
        this.$message.error('搜索关键词不能为空')
        return false
      }
      if (this.article.imgUrl.trim() == '') {
        this.$message.error('资讯封面图片不能为空')
        return false
      }
      if (this.article.content.trim() == '') {
        this.$message.error('资讯内容不能为空')
        return false
      }
      this.$http[!this.article.id ? "post" : "put"]('/health/articles', this.article).then(({ data: res }) => {
        if (res.code == 0) {
          this.$store.state.contentTabs = this.$store.state.contentTabs.filter(item => item.name === 'articles-list')
          this.$router.replace({ name: 'articles-list' })
          this.$message({
            message: '创建成功',
            type: 'success'
          });
        } else {
          this.$message.error('创建失败');
        }
        this.addOrEdit = false
      })
      this.autoSave = false
    }
  }
}
</script>

<style scoped>
.article-title-container {
  display: flex;
  align-items: center;
  margin-bottom: 1.25rem;
  margin-top: 2.25rem;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
